import { useSyncExternalStore } from 'react';

//监听history变化
export const useHistory = () => {
    const subscribe = (callback: () => void) => {
        window.addEventListener('popState', callback);
        window.addEventListener('hashChange', callback);
        return () => {
            window.removeEventListener('popState', callback);
            window.removeEventListener('hashChange', callback);
        };
    };
    const getSnapshot = () => {
        return window.location.href
    };

    const url = useSyncExternalStore(subscribe, getSnapshot);
    const push = (url: string) => {
        window.history.pushState({}, '', url);
        window.dispatchEvent(new PopStateEvent('popState'))
    };
    const replace = (url: string) => {
        window.history.replaceState({}, '', url);
        window.dispatchEvent(new PopStateEvent('popState'))
    };
    return [url, push, replace] as const;
};
